package cn.demo.weixin.mp.config;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.service.WxOAuth2Service;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpOAuth2ServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 微信公众号配置
 */
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WxMpProp.class)
@Slf4j
public class WxMpConfig {

    private final WxMpProp properties;

    @Bean(name = "wxMpService")
    public WxMpService wxMpService() {

        WxMpService service = new WxMpServiceImpl();
        if (properties.getAppId() == null || properties.getSecret() == null) {
            log.info("请配置微信公众号的appid和secret，如不需要请删除代码");
            return service;
        }

        WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
        configStorage.setAppId(properties.getAppId());
        configStorage.setSecret(properties.getSecret());
        configStorage.setToken(properties.getToken());
        configStorage.setAesKey(properties.getAesKey());

        service.setWxMpConfigStorage(configStorage);
        return service;
    }
    @Bean(name = "wxOAuth2Service")
    public WxOAuth2Service wxOAuth2Service(WxMpService wxMpService) {

        return new WxMpOAuth2ServiceImpl(wxMpService);
    }

    @Bean(name = "wxMpMessageRouter")
    public WxMpMessageRouter wxMpMessageRouter(WxMpService wxMpService) {
        final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService);
        return newRouter;
    }

}
